import json
import time
import redis
import datetime
import template
class Log_analy():
     domaintopn = 'domaintopn'
     clienttopn = 'iptopn'
     domainqps = 'domainqps'
     viewqps = 'qps'
     mutual_ip = 'domainip'
     mutual_domain = 'ipdomain'
     totalquery = "totalquery"
     rtype = 'rtype'
     recursion = 'recursion'
     rcode = 'rcode'
     edns = 'edns'
     tcp = 'tcp'
     sign = 'sign'
     dnssec = 'dnssec'
     cd = 'cd'
     def __init__(self, host='localhost', port=6379):
         self.redis = redis.StrictRedis(host=host,port=port)
     def all_options(self):
         options = {self.domaintopn:"topn", self.clienttopn:"topn", self.totalquery:"NULL", self.rtype:"NULL", self.recursion:"NULL",\
                    self.domainqps:"domain-name", self.viewqps:"NULL", self.mutual_ip:"domain", self.mutual_domain:"ip",self.rcode:"NULL",self.edns:"NULL",
                    self.tcp:"NULL", self.sign:"NULL", self.dnssec:"NULL", self.cd:"NULL"}
         return json.dumps(options)
     def option_exists(self, option):
         if option in self.all_options():
             return True
         return False
     def set_config(self, opts):
         template.main(opts)
         print "gen rsyslog config ok"
         return "ok"
     def execute_query(self, view, key, para):
         result = {}
         if key == self.domaintopn or key == self.clienttopn: 
             result = self.get_topn(view, key, para)
         return json.dumps(result)
     def get_topn(self, view, option, top_num = 1):
         result = self.redis.zrevrange(view + ':' + option, 0, int(top_num) - 1, withscores=True)
         return [[item[0],item[1]] for item in result]

     def get_property(self, view, key):
         return json.dumps(self.get_others(view, key))
     def get_ipaddr(self, view):
         #total = json.loads(self.get_totalquery(view))
         tq = self.redis.get(view + ':' + self.totalquery)
         if not tq: tq = '0'
         ipv6 = 0
         all_key_list = self.redis.keys(view + ':' + '*')
         for key in all_key_list:
             ip = key.split(':', 2)[-1]
             if ip.find(':') != -1:
                context =  self.redis.zrange(key, 0, -1, withscores=True)
                for elem in context:
                    ipv6 += elem[1]
         result = {"ipv4":int(tq) - ipv6, "ipv6":ipv6}
         print result
         return json.dumps(result)
     def get_totalquery(self, view): 
         print view
         tq = 0.0
         all_key_list = self.redis.keys(view + ':' + self.totalquery)
         for key in all_key_list:
		 	view_tq = float(self.redis.get(key))
			if not view_tq: view_tq = 0
			tq = tq + view_tq
         return {self.totalquery:tq}
     def get_others(self, view, key):
         result = self.redis.zrange(view + ':' + key, 0, -1, withscores=True) 
         return result
     def get_view_qps(self, view):
         qps1 = float(self.get_totalquery(view)['totalquery'])
         s1 = datetime.datetime.now()
         time.sleep(0.1)
         qps2 = float(self.get_totalquery(view)['totalquery'])

         s2 = datetime.datetime.now()
         print "q2 %f, q1 %f" % (qps2, qps1)
         #print "total seconds", (s2- s1).total_seconds()
         delta = s2 - s1
         dur = delta.seconds + float(delta.microseconds*1.0/1000000)
         return json.dumps({self.viewqps:((qps2 - qps1) / (dur))})

     def get_mutual_info(self, view, mutual_key, top_num=0):
         result = self.redis.zrevrange(view + ':' + mutual_key, 0, int(top_num) - 1, withscores=True) 
         return json.dumps([[item[0], item[1]] for item in result])

     def get_domain_accessed_num(self, view, domain_name):
         result = json.loads(self.get_mutual_info(view, domain_name, 0))
         total = 0
         for item in result:
             print item
             total += item[1]
         return total
         
     def get_domain_qps(self, view, domain_name):
         qps1 = self.get_domain_accessed_num(view, domain_name)
         s1 = datetime.datetime.now()
         time.sleep(0.1)
         qps2 = self.get_domain_accessed_num(view, domain_name)
         s2 = datetime.datetime.now()
         delta = s2 - s1
         dur = delta.seconds + float(delta.microseconds*1.0/1000000)
         print "total seconds", dur
         return json.dumps([domain_name, ((qps2 - qps1) / (dur))])
     def get_all_stats(self, view, topn=10):
         all_stats = {}
         all_stats[self.domaintopn] = self.execute_query(view, self.domaintopn, topn) 
         all_stats[self.clienttopn] = self.execute_query(view, self.clienttopn, topn)
         all_stats[self.totalquery] = self.get_totalquery(view)
         all_stats[self.rtype] = self.get_property(view, self.rtype)
         all_stats[self.recursion] = self.get_property(view, self.recursion)
         all_stats[self.rcode] = self.get_property(view, self.rcode)

         return json.dumps(all_stats)
